<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
  <script src="./js/lodash.min.js"></script>
  <script>
    function Cart() {
      this.items = []
    }
    // JSON方式进行递归
    Cart.prototype.deepCopy = function (obj) {
      return JSON.parse(JSON.stringify(obj))
    }

    // 添加
    Cart.prototype.addCart = function (data) {
      const index = this.items.findIndex((item) => item.id === data.id)
      // 如果存在了商品则加上商品的数量
      if (index >= 0) {
        this.items[index].quantity += data.quantity
      } else {
        // 如果没有则添加商品
        this.items.push(this.deepCopy(data))
      }
    }

    // 删除
    Cart.prototype.removeCart = function (id) {
      const index = this.items.findIndex((item) => {
        return item.id === id
      })
      return this.items.splice(index, 1)
    }

    // 清空
    Cart.prototype.clear = function () {
      this.items = []
    }

    // 修改
    Cart.prototype.updateCart = function (id, quantity) {
      const index = this.items.findIndex((item) => item.id === id)
      if (index >= 0) {
        this.items[index].quantity = quantity
      }
    }

    // 总价
    Cart.prototype.totalPrice = function () {
      const num = this.items.reduce((prev, item) => {
        return prev + item.price * item.quantity
      }, 0)
      console.log(num)
      return num
    }

    // 防抖
    Cart.prototype.debouncePrice = _.debounce(Cart.prototype.totalPrice, 1000)

    const cart = new Cart()
    const item = { id: 1, name: '手机', price: 3999, quantity: 2 }
    const item1 = { id: 2, name: '电脑', price: 13999, quantity: 4 }
    const item2 = { id: 3, name: '平板', price: 6999, quantity: 5 }
    const item3 = { id: 1, name: '手机', price: 3999, quantity: 2 }

    // 添加
    cart.addCart(item)
    cart.addCart(item1)
    cart.addCart(item2)

    cart.addCart(item3)

    console.log(cart)
    console.log(cart.items)

    // 删除
    cart.removeCart(2)

    // 清空
    // cart.clear()

    // 修改
    // cart.updateCart(3, 8)

    // 总和
    cart.debouncePrice()
    console.log(cart.items)
  </script>
</html>
